package com.cjb.cloudmqtt.mqtt.config;

import com.cjb.cloudmqtt.mqtt.subscribe.MqttConsumerCallBack;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

/**
 * @Author chenjinbin
 * @Package IntelliJ IDEA
 * @Class MqttConfig
 * @Date 2023-09-21 1:33
 */
@Configuration
@Slf4j
public class MqttConfig {
    @Value("${spring.mqtt.username}")
    private String username;

    @Value("${spring.mqtt.password}")
    private String password;

    @Value("${spring.mqtt.url}")
    private String hostUrl;

    @Value("${spring.mqtt.client.id}")
    private String clientId;

    @Value("${spring.mqtt.default.topic}")
    private String defaultTopic;

    @Value("${spring.mqtt.timeout}")
    private Integer timeout;

    @Value("${spring.mqtt.keepalive}")
    private Integer keepalive;

    private static final String SECRET = "eXhx";

    @Autowired
    private MqttConsumerCallBack mqttConsumerCallBack;

    private static String generateToken(String password) {
        JwtBuilder jwtBuilder = Jwts.builder();

        String jwtToken = jwtBuilder
                //header
                .setHeaderParam("alg", "HS256")
                .setHeaderParam("typ", "JWT")
                //payload
                .claim("password", "admin")
//                .claim("clientid", "yxq_test")
//                .setSubject("lieh")
//                .setIssuedAt(Date.from(Instant.now()))
//                .setExpiration(new Date(System.currentTimeMillis() + time)) //有效时间1天
//                .setId("yxq_test")
                //signature
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
        return jwtToken;
    }

    @Bean
    public MqttClient mqttClient() throws MqttException {
        MqttClient client = new MqttClient(hostUrl, clientId, new MemoryPersistence());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);
        options.setUserName(username);

        // 生成 JWT 令牌作为 MQTT 连接密码
        log.info("----------------------");
        options.setPassword(password.toCharArray());
        log.info("======================");
        options.setConnectionTimeout(timeout);
        options.setKeepAliveInterval(keepalive);
        options.setAutomaticReconnect(true);
        options.setWill(defaultTopic, (clientId + "与服务器断开连接").getBytes(), 0, true);
        client.setCallback(mqttConsumerCallBack);
        client.connect(options);
        return client;
    }
}
